<template>
	<el-row :gutter="20">
		<el-col :span="8">
			<el-card class="box-card">
				<template #header>
					<div class="card-header">头像信息</div>
				</template>
				<div class="text item">
					<div class="avatar">
						<el-avatar class="avatar" shape="square" :size="50" :src="avatarURL" />
					</div>
					<el-upload ref="uploadRef" class="upload-demo" :limit="1" :action="uploadURL" :headers="headers" :data="uploadData" :auto-upload="false" :on-success="uploadSuccess">
						<template #trigger>
							<p><el-button type="primary">选择头像</el-button></p>
						</template>
						<div>
							<el-button type="success" @click="submitUpload">上传头像</el-button>
						</div>
						<template #tip>
							<div class="el-upload__tip"><p>限制上传1个文件，且旧文件会被新文件覆盖</p></div>
						</template>
					</el-upload>
				</div>
			</el-card>
		</el-col>
		<el-col :span="16">
			<el-card class="box-card">
				<template #header>个人信息</template>
				<div class="change-password-box">
					<el-form ref="ruleFormRef" status-icon :model="form" :rules="rules" label-width="140px">
						<el-form-item prop="password" label="修改密码">
							<el-input type="password" v-model="form.password" />
						</el-form-item>
						<el-form-item prop="password2" label="请再次输入密码">
							<el-input type="password" v-model="form.password2" />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
							<el-button @click="resetForm">重置</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-card>
		</el-col>
	</el-row>
</template>

<script setup>
import { ref, reactive } from 'vue'
import defaultAvatarURL from '/images/avatar-default.png'
import { changeAdminPassword, changeAdminAvatar, uploadPictureURL } from '../../api'
import notification from '../../utils/notification'
import useToken from '../../stores/token'
import useAdmin from '../../stores/admin'
import router from '../../router'

const { admin, updateAdmin, removeAdmin } = useAdmin()
const { token, removeToken } = useToken()
const headers = { token: token }

const uploadURL = uploadPictureURL()
const uploadData = { type: 'admin_avatar' }

const form = reactive({
	password: '',
	password2: '',
})
const avatarURL = ref(admin.avatar || defaultAvatarURL)
const ruleFormRef = ref()
const uploadRef = ref()

////////////////// 修改头像///////////////////////////////
const submitUpload = () => {
	uploadRef.value.submit() // 触发文件上传请求
}

// 请求成功后执行
const uploadSuccess = async response => {
	console.log('uploadSuccess', response)

	const { code, msg, data } = response
	if (code !== 0) {
		notification({
			message: msg,
			type: 'error',
		})
	} else {
		notification({
			message: msg,
			type: 'success',
		})
		// 根据文件上传返回保存地址，提交头像修改请求
		await changeAdminAvatar({
			avatar: data.image,
		})
		// 更新pinia保存的头像信息
		updateAdmin({
			avatar: data.image,
		})
		// 更新当前上传组件的文件预览
		avatarURL.value = data.image
	}
	uploadRef.value.clearFiles()
}

//////////// 修改密码/////////////////////////////////
// 提交修改请求
const submitForm = formEl => {
	formEl.validate(async valid => {
		if (valid) {
			await changeAdminPassword({ password: form.password })
			resetForm()
			// 退出登录
			removeToken()
			removeAdmin()
			router.push({ name: 'login' })
			notification({
				message: '修改密码后，请重新登录',
				type: 'warning',
			})
		} else {
			notification({
				message: '表单填写有误',
				type: 'error',
			})
		}
	})
}

// 重置表单
const resetForm = () => {
	ruleFormRef.value.resetFields()
}

// 验证密码
const validatePass = (rule, value, callback) => {
	if (value !== form.password) {
		callback(new Error('两次输入密码不一致！'))
	} else {
		callback()
	}
}

const rules = reactive({
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 6, max: 24, message: '密码长度为6~24个字符', trigger: 'blur' },
	],
	password2: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ validator: validatePass, trigger: 'blur' },
	],
})
</script>

<style lang="scss" scoped>
.avatar {
	text-align: center;
}
.upload-demo {
	text-align: center;
}
.box-card {
	height: 316px;
}
.change-password-box {
	padding-top: 38px;
}
</style>
